/*
 * @(#)UserTimeOutInterceptor.java $version 2013. 5. 30.
 *
 */

package com.pace.gonu.intercepter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.pace.gonu.model.chnl.PlayChannel;
import com.pace.gonu.play.PlayService;

/**
 * @author pace
 */
public class UserAuthInterceptor extends HandlerInterceptorAdapter {
	@Autowired
	private PlayService playService;

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
		HttpSession session = request.getSession();
		String authKey = (String)session.getAttribute("AUTH_KEY");
		Integer chnlNumber = (Integer)session.getAttribute("CHANNEL_NUMBER");
		
		if (chnlNumber == null || StringUtils.isBlank(authKey)) {
			response.sendRedirect("/gonu/home.gonu");
		}

		PlayChannel playChannel = playService.getChannel(chnlNumber);
		
		if (StringUtils.equals(authKey, playChannel.getFirstAuthKey())) {
			return true;
		} else if (StringUtils.equals(authKey, playChannel.getSecondAuthKey())) {
			return true;
		}

		if (playChannel.isPVC()) {
			response.sendRedirect("/gonu/home.gonu");
		} else {
			response.sendRedirect("/gonu/play/chnlSelect.gonu");
		}
		
		return true;
	}
}
